/*
 * 文 件 名:  BaseController.java
 * 版    权:  kuanrf  Co., Ltd. Copyright YYYY-YYYY,  All rights reserved
 * 描    述:  <描述>
 * 修 改 人:  sheng.li
 * 修改时间:  2015年4月15日
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.saile.controller.base;


import com.saile.def.Constant;
import com.saile.domain.User;
import com.saile.domain.ViewsQuantity;
import com.saile.log.LogFactory;
import com.saile.service.ViewsQuantityService;
import com.saile.util.FileTools;
import com.saile.util.LoadPic;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


/**
 * <一句话功能简述>
 * <功能详细描述>
 *
 * @author sheng.li
 * @version [版本号, 2015年4月15日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public abstract class BaseController {

    protected Logger logger = LogFactory.getLogger(getClass());
    @Autowired
    protected  HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;
    @Autowired
    protected HttpSession session;


    @Autowired
    ViewsQuantityService viewsQuantityService;
    protected void  addViewsQuantity(Long resourceId,String resourceType){
        ViewsQuantity viewsQuantity=new ViewsQuantity();

        viewsQuantity.setAmount(1);
        viewsQuantity.setResourceId(resourceId);
        viewsQuantity.setResourceType(resourceType);
        viewsQuantity.setCreateTime(new Date());
        viewsQuantityService.insertViewsQuantity(viewsQuantity);
        logger.info("阅读量+1");
    }

    protected void getCookie() {
        Cookie[]  cookies=request.getCookies();
        User user=new User();
        if(cookies!=null && cookies.length>0){


        for (Cookie cookie: cookies
             ) {
            if(cookie.getName().equals("user_id")){
                user.setTid(Long.parseLong(cookie.getValue().toString()));
            }

            if(cookie.getName().equals("username")){

                logger.info("username====>>>:"+cookie.getValue().toString());
                try {
                    String username = URLDecoder.decode(cookie.getValue().toString(), "utf-8");
                    user.setUserName(username);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }  if(cookie.getName().equals("nickname")){
                logger.info("nickname====>>>:"+cookie.getValue().toString());
                try {
                    String nickname = URLDecoder.decode(cookie.getValue().toString(), "utf-8");
                    user.setNickName(nickname);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        }
        if(user.getTid()!=null){
            session.setAttribute(Constant.SESSION_KEY_USER_LOGIN,user);
        }
    }
    protected User getUserBySession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Constant.SESSION_KEY_USER_LOGIN);
        return user;
    }

    protected Map<String, String> showRequestParameters() {

        Enumeration<?> paramNames = request.getParameterNames();
        Map<String, String> map = new HashMap<String, String>();
        while (paramNames.hasMoreElements()) {

            String paramName = paramNames.nextElement().toString();
            String paramValue = request.getParameter(paramName);
            map.put(paramName, paramValue);
            System.out.println(paramName + "[:]" + paramValue);
        }

        try {
            User user = (User) request.getSession().getAttribute(Constant.SESSION_KEY_USER_LOGIN);
            if (user != null) {
                map.put("userId", String.valueOf(user.getTid()));
            }

        } catch (Exception e) {
            logger.info(e.getMessage());
        }


        return map;
    }

    protected String upLoadFile(MultipartFile location)  throws  Exception{
        String filePath = FileTools.getUniquenessName("") + FileTools.PICTURE_SUFFIX_JPG;
        logger.info("filePath===>>>"+filePath);

        LoadPic.LoadPics(location, filePath);
        return filePath;
    }
    protected Map<String, String> upLoadFile(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            System.out.println(fileMap.size());
            for (String key : fileMap.keySet()) {
                System.out.println("key= " + key + " and value= " + map.get(key));
                String filePath = FileTools.getUniquenessName("") + FileTools.PICTURE_SUFFIX_JPG;
                System.out.println("filepath" + filePath);
                MultipartFile multipartFile = fileMap.get(key);
                System.out.println("file.getSize()===>>>" + multipartFile.getSize());
                byte[] bytes = multipartFile.getBytes();
                LoadPic.LoadPics(multipartFile, filePath);
            /*	BufferedOutputStream stream =
						new BufferedOutputStream(new FileOutputStream(new File("/static/images/"+filePath)));
				stream.write(bytes);
				stream.close();*/
                map.put(key, filePath);
            }

            //上传文件

        } catch (Exception e1) {
logger.info("upload  erro====>>>"+e1);
            e1.printStackTrace();
        }
        return map;
    }







}
